import { createRouter, createWebHashHistory } from 'vue-router'
import pinia from '@/store'
import Login from '@/views/common/login/LoginView.vue'
import Print from '@/views/common/print/PrintView.vue'
import MainView from '@/views/MainView.vue'
import HomeView from '@/views/home/IndexView.vue'
import { getToken } from '@/utils'
import { toPromise } from '@xuekl/cli-utils'
// import http from '@/utils/httpRequest'
import genRoutes from './routes'
import useApp from '@/store/app'
import { SideMenu } from '@xuekl/cli-base/type'
const appStore = useApp(pinia)

const gloabRoutes = [
    { path: '/login', name: 'login', component: Login },
    { path: '/print', name: 'print', component: Print },
]

const routes = [
    ...gloabRoutes,
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/',
        name: 'Main',
        component: MainView,
        children: [
            {
                path: '/home',
                name: 'Home',
                component: HomeView,
            },
            ...genRoutes
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})


export async function startPromise() {
    const vals = await toPromise(() => appStore.menus, true)
    genRouter(vals)
}

function genRouter(vals: SideMenu[]) {

    let modules = import.meta.glob(`../views/module/**/*.vue`)

    function innerGen(accept: SideMenu[]) {
        accept.forEach((val: SideMenu) => {
            if (val.type === 'file') {
                const menu = {
                    path: val.fullPath || val.path,
                    name: val.fullName || val.name,
                    component: modules[`../views/module/${val.component}/IndexView.vue`],
                    meta: val.meta
                }

                router.addRoute("Main", menu)
            } else {
                if (val.children) {
                    innerGen(val.children)
                }
            }
        })
    }

    innerGen(vals)

    router.addRoute(
        {
            path: "/:pathMatch(.*)",
            redirect: "/"
        }
    )
}


router.beforeEach((to, _from, next) => {
    if (getToken() || gloabRoutes.some(route => route.name === to.name)) {
        next()
    } else {
        next({
            path: '/login'
        })
        // http({
        //     url: http.adornUrl('/login'),
        //     method: 'post',
        //     data: http.adornData({
        //         username: 'admin',
        //         // password: '123456'
        //         // username: 'huangyingit@hq.cmcc',
        //         password: 'admin123'
        //     })
        // }).then(({ data }) => {
        //     if (data.code === 200) {
        //         setToken(data.token)
        //         startPromise()
        //         next()
        //     }
        // })
    }
})

export default router
